﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using SuraQR.Bean;
using SuraQR.Controller;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using SuraQR.Config;
using System.Reflection;
using System.IO.Compression;
using System.Collections;

namespace SuraQR
{
    public partial class luncher : Form
    {
        private BindingSource b, t3;

        public BindingSource T3
        {
            get { return t3; }
            set { t3 = value; }
        }

        public BindingSource B
        {
            get { return b; }
            set { b = value; }
        }

        
            
        public luncher()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            tab1AddrBlinding.AddNew();
        }

         private void btnOrderAdd_Click(object sender, EventArgs e)
         {
             Debug.WriteLine("ADD");
             OrderDetailFrm keyInOrder = new OrderDetailFrm();
             keyInOrder.ShowDialog();
             if (keyInOrder.AddNewOrder != null)
             {
                 tab2OrderList.Add(keyInOrder.AddNewOrder);
                 setRowNumber(orderList);
                 orderList.Refresh();
             }
           
         }

         private void luncher_Load(object sender, EventArgs e)
         {
             // init data
             if (tab1AddrBlinding.List.Count == 0)
             {
                 Debug.WriteLine("Addrdess new ");
                 tab1AddrBlinding.AddNew();               
             }            

             // tab3
             if (tab3Tax.List.Count == 0)
             {
                 tab3Tax.AddNew();
             }
             else
             {
                Tax t = (Tax)tab3Tax.List[0];
                radioButtonCheck(radioButton1, t.TaxTypeRadio);
                radioButtonCheck(radioButton2, t.TaxTypeRadio);
                radioButtonCheck(radioButton3, t.TaxTypeRadio);
             }

             //staff
             if (tab1Staff.List.Count == 0)
             {
                 tab1Staff.AddNew();
             }

             T3 = tab3Tax;
             this.B = tab1AddrBlinding;

             //version
             lblVersion.Text = "Version : " + SuraQR.Config.PropertiesConfig._AppVersin;

             // load menu
            XmlToMenuService menu = new XmlToMenuService();
            menu.read();
            ServerRuntimeSingleton.Instance.MenuList = menu;

             //debug

            TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
            Debug.Listeners.Add(tr1);

            TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt"));
            Debug.Listeners.Add(tr2);
            Debug.Unindent();
            Debug.WriteLine("xxxxxxxxxxxxxxxxxxxxxxxx");

         }
         private void radioButtonCheck(RadioButton r, string v)
         {
             bool chk =  (r.Text.Equals(v)) ? true : false;
             if (chk)
                 r.Checked = true;

             Debug.WriteLine("radio : " + v + " : " + r.Checked);
         }
         public void showWithData(SOROR12011 dumpData)
         {
             tab1AddrBlinding.List.Clear();
             tab1AddrBlinding.List.Add(dumpData.Addr);

             tab1Staff.List.Clear();
             tab1Staff.List.Add(dumpData.Straff);

             tab2OrderList.List.Clear();
             foreach (Order d in dumpData.OrderList)
             {
                 tab2OrderList.List.Add(d);
             }

             tab3Tax.List.Clear();
             Debug.WriteLine("###" + dumpData.Tax);
             Debug.WriteLine("###" + dumpData.Tax.Data14);
             tab3Tax.List.Add(dumpData.Tax);

             // show
             this.ShowDialog();

         }

         private void orderList_CellContentClick(object sender, DataGridViewCellEventArgs e)
         {

         }

         private void setRowNumber(DataGridView dgv)
         {
             foreach (DataGridViewRow row in dgv.Rows)
             {
                 row.HeaderCell.Value = (row.Index + 1).ToString();
             }
         }

         private void btnOrderEdit_Click(object sender, EventArgs e)
         {
             Debug.WriteLine("EDIT");
             OrderDetailFrm keyInOrder = new OrderDetailFrm();
             keyInOrder.IsEdit = true;
             if (tab2OrderList.Current != null)
             {
                 keyInOrder.AddNewOrder = (Order)tab2OrderList.Current;
                 keyInOrder.ShowDialog();
                 orderList.Refresh();
             }
             Debug.WriteLine("edit");
         }

         private void btnOrderDel_Click(object sender, EventArgs e)
         {
             if (tab2OrderList.Current != null)
             {
                 DialogResult dialogResult = MessageBox.Show("ยืนยันการลบ ข้อมูล", "ยืนยันการลบ", MessageBoxButtons.YesNo);
                 if (dialogResult == DialogResult.Yes)
                 {
                     tab2OrderList.Remove(tab2OrderList.Current);
                     setRowNumber(orderList);
                 }
                
             }
         }

         private void btn_GenQrClick(object sender, EventArgs e)
         {
             QRCodeGenService qr = new QRCodeGenService();
             SOROR12011 raw = new SOROR12011();
             String p5 = Config.PropertiesConfig._AppVersin;

             F1Address p1 = (F1Address) tab1AddrBlinding.List[0];
             Straff p2 = (Straff)tab1Staff.List[0];

             Order[] p3 = new Order[tab2OrderList.List.Count];
             for (int i = 0; i < tab2OrderList.List.Count; i++)
             {
                 p3[i] = (Order)tab2OrderList.List[i];
             }
            

             ArrayList ordersTmp = new ArrayList();
             for (int i = 0; i < tab2OrderList.List.Count; i++)
             {
                 SOROR12011 t = new SOROR12011();
                 Order[] o = new Order[1];
                 o[0] = (Order)tab2OrderList.List[i];
                 t.OrderList = o;
                 raw.Version = p5;
                 ordersTmp.Add(t);
             }
    
            
             Tax p4 = (Tax)tab3Tax.List[0];
            
            

 /*         raw.Addr = p1;
             raw.Straff = p2;
             raw.OrderList = p3;
             raw.Tax = p4;
             raw.Version = p5;
 */
            //convert
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            //1 Address
            raw.Addr = p1;
            raw.Straff = null;
            raw.OrderList = null;
            raw.Tax = null;
            raw.Version = p5;
            formatter.Serialize(stream, raw);
            
            byte[] zip = SRUtils.Zip(stream.ToArray());

            string addrBase64 = Convert.ToBase64String(zip.ToArray());
            Debug.WriteLine("----");
            Debug.WriteLine("OLD : " + stream.ToArray().Length);
            Debug.WriteLine("Zip : " + zip.Length);
            Debug.WriteLine("1 Address : " + addrBase64.Length);


            //2 OrderList
            /*            raw.Addr = null;
                        raw.Straff = null;
                        raw.OrderList = p3;
                        raw.Tax = null;
                        raw.Version = p5;
            */
            ArrayList orderbase64List = new ArrayList();
            if (ordersTmp.Count > 0)
            {
                foreach (SOROR12011 sr in ordersTmp)
                {
                    stream.Close();
                    stream = new MemoryStream();
                    formatter.Serialize(stream, sr);

                    zip = SRUtils.Zip(stream.ToArray());

                    string ordersBase64 = Convert.ToBase64String(zip.ToArray());
                    Debug.WriteLine("----");
                    Debug.WriteLine("OLD : " + stream.ToArray().Length);
                    Debug.WriteLine("Zip : " + zip.Length);
                    Debug.WriteLine("2 OrderList : " + ordersBase64.Length);
                    orderbase64List.Add(ordersBase64);

                }
            }
            else
            {
                stream.Close();
                stream = new MemoryStream();
                SOROR12011 sr = new SOROR12011();
                sr.Version = p5;
                formatter.Serialize(stream, sr);

                zip = SRUtils.Zip(stream.ToArray());

                string ordersBase64 = Convert.ToBase64String(zip.ToArray());
                Debug.WriteLine("----");
                Debug.WriteLine("OLD : " + stream.ToArray().Length);
                Debug.WriteLine("Zip : " + zip.Length);
                Debug.WriteLine("2 OrderList : " + ordersBase64.Length);
                orderbase64List.Add(ordersBase64);
            }
         
     
           
            //3 Tax
            raw.Addr = null;
            raw.Straff = null;
            raw.OrderList = null;
            raw.Tax = p4;
            raw.Version = p5;
            stream.Close();
            stream = new MemoryStream();
            formatter.Serialize(stream, raw);

            zip = SRUtils.Zip(stream.ToArray());

            string taxBase64 = Convert.ToBase64String(zip.ToArray());
            Debug.WriteLine("----");
            Debug.WriteLine("OLD : " + stream.ToArray().Length);
            Debug.WriteLine("Zip : " + zip.Length);
            Debug.WriteLine("3 Tax : " + taxBase64.Length);
            stream.Close();


           

            //QR
            Debug.WriteLine("################### GEN QR ######################");
            // 1
            string[] tmp = qr.subQRCode(addrBase64);
            String[] addQr = qr.genQR(tmp);
            Debug.WriteLine("QR : ADDR : " + addQr.Length);

            // 2
            //orderbase64List
            ArrayList imageQr = new ArrayList();
            foreach (string s in orderbase64List)
            {
                string[] tmp2 = qr.subQRCode(s);
                String[] orderQr = qr.genQR(tmp2);
                Debug.WriteLine("QR : ORDER : " + orderQr.Length);
                imageQr.Add(orderQr);
            }

            // 3
            string[] tmp3 = qr.subQRCode(taxBase64);
            String[] taxQr = qr.genQR(tmp3);
            Debug.WriteLine("QR : TAX : " + taxQr.Length);

            Debug.WriteLine("################ END GEN QR ######################");
            if (addQr.Length > 0 && imageQr.Count > 0 && taxQr.Length > 0)
            {
                MessageBox.Show("เรียบร้อย");
              
               String[] images = new String[imageQr.Count + 2];
                images[0] = addQr[0];
                images[1] = taxQr[0];

                for (int i = 0; i < imageQr.Count; i++)
                {
                    images[2 + i] = ((string[])imageQr[i])[0];
                }

                //for detail
                raw.Addr = p1;
                raw.Straff = p2;
                raw.OrderList = p3;
                raw.Tax = p4;
                raw.Version = p5;

                qr.openDoc(images,raw);

                Debug.Flush();
            }
            else
            {
                MessageBox.Show("สร้าง QR Code ไม่ได้");
            }

        }

  
        private void button1_Click_1(object sender, EventArgs e)
        {
            dataMorniter m = new dataMorniter();
            m.Lun = this;
            m.Show();
        }

        private void radioCheckedChanged(object sender, EventArgs e)
        {
           
            if (tab3Tax.List.Count > 0)
            {
                RadioButton rd = (RadioButton)sender;
                Tax t = (Tax)tab3Tax.List[0];
                t.TaxTypeRadio = rd.Text;
            }
         
        }



        private void calcOrderTax()
        {
            Debug.WriteLine("cal Tax");
            if (tab2OrderList.List.Count == 0)
            {
                Debug.WriteLine("No order cal in calcOrderTax");
                return;
            }

            //calc

            double sumAdTax = 0;
            double sumQty = 0;

            foreach (Order o in tab2OrderList.List)
            {
                sumAdTax += o.TotalAdValoremTax;
                sumQty += o.TotalQuantityTax;
            }

            Tax t = (Tax) tab3Tax.List[0];

            t.Data6_1_2 = Math.Round( sumAdTax , 2 );

            t.Data6_1 = Math.Truncate(sumAdTax);

            t.Data6_2 = sumQty;

            t.Data7 = t.Data6_1 + t.Data6_2;

            t.Data9 = t.Data7 - t.TaxRoyalReturn;
            t.Data10 = t.Data9;
            t.Data11 = (t.Data10 * t.TaxMinistryOfInterior) / 100;
            t.Data12 = t.Data10 + t.Data11;
            t.Data13 = t.Data12;
            //t.Data14 
            t.Data15 = t.Data14 + t.Data13;

            tab3Tax.ResetBindings(false);
            
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            TabControl t = (TabControl)sender;
            Debug.WriteLine("Tab : " + t.SelectedTab.Name);
            Debug.WriteLine("Tab : " + t.SelectedIndex);
            if (t.SelectedIndex == 2)
            {
                this.calcOrderTax();
            }
        }
           
                      
    }
}
